package cn.com.czpb.client.module.news.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import cn.com.czpb.client.R;
import cn.com.czpb.client.api.InterfaceJsonfile;
import cn.com.czpb.client.app.ToolBarActivityWhite;
import cn.com.czpb.client.custorm.RecycleViewDivider;
import cn.com.czpb.client.custorm.smartrefreshalayout.ClassHeader_other;
import cn.com.czpb.client.model.news.ComResultEntity;
import cn.com.czpb.client.model.news.CommBean;
import cn.com.czpb.client.model.news.CommEntity;
import cn.com.czpb.client.model.news.NewsDetailBean;
import cn.com.czpb.client.module.news.adapter.NewsCommentAdapter;
import cn.com.czpb.client.net.Factory;
import cn.com.czpb.client.utils.ActionbarUtils;
import cn.com.czpb.client.utils.DeviceUtils;
import cn.com.czpb.client.utils.LogUtils;
import cn.com.czpb.client.utils.PageCtrl;
import cn.com.czpb.client.utils.ParamUtils;
import cn.com.czpb.client.utils.TUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class CommentActivity extends ToolBarActivityWhite implements OnRefreshListener,
        OnRefreshLoadmoreListener {
    @BindView(R.id.swipe_layout)
    SmartRefreshLayout swipe_layout;
    @BindView(R.id.ptrlistview_activity_collection)
    RecyclerView recyclerview_comm;
    List<CommBean> list;
    NewsCommentAdapter adapter;
    @BindView(R.id.img_back_id)
    ImageView img_back_id;
    @BindView(R.id.ll_empty)
    ImageView ll_empty;
    @BindView(R.id.back_toolbar)
    TextView back_toolbar;
    @BindView(R.id.tv_empty_collection_activity)
    TextView tv_empty_collection_activity;
    private int Page = 1;
    private static final int PageSize = 15;
    private boolean mFlagRefresh = true;
    private String type;
    private String newstype;
    private String nid;
    private String newsid;
    private NewsDetailBean ndb;
    private boolean isRePlyUSer=false;//是否回复用户
    private String USERNANME;
    private String CID;
    private int f_position;
    private int position;
    private GetUserInfo getUserInfobr;

    public static String SEND_MSG="com.hdkj.guangxi.sendmsg";
    public static String PRASE="com.hdkj.guangxi.priase";
    @Override
    public int setMyContentView() {
        return R.layout.activity_comm;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //状态栏字体颜色设置成深色
        ActionbarUtils.setMeizuStatusBarDarkIcon(activity, true);
        ActionbarUtils.setMiuiStatusBarDarkMode(activity, true);
        init();
        initBR();
        settitleBg();
        img_back_id.setImageResource(R.drawable.black_back);
        back_toolbar.setTextColor(getResources().getColor(R.color.color_1a1a1a));
        et_send.setVisibility(View.VISIBLE);
        tv_send.setVisibility(View.VISIBLE);
    }
    private void initBR(){
        getUserInfobr = new GetUserInfo();
        IntentFilter filter = new IntentFilter();
        filter.addAction(SEND_MSG);
        filter.addAction(PRASE);
        activity.registerReceiver(getUserInfobr, filter);
    }
    private void init() {
        nid = getIntent().getStringExtra("nid");
        newsid = getIntent().getStringExtra("newsid");
        ndb = (NewsDetailBean) getIntent().getSerializableExtra("newsbean");
        type = getIntent().getStringExtra("type");
        newstype = getIntent().getStringExtra("newstype");






        list = new ArrayList<>();
        adapter = new NewsCommentAdapter(list, nid, newstype, activity);
        initList();
        int height = (int) getResources().getDimension(R.dimen.x2);
        recyclerview_comm.addItemDecoration(new RecycleViewDivider(activity,
                LinearLayoutManager.HORIZONTAL, height,
                getResources().getColor(R.color.color_e8e8e8)));
        LinearLayoutManager manager = new LinearLayoutManager(activity);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerview_comm.setLayoutManager(manager);
        recyclerview_comm.setAdapter(adapter);
        swipe_layout.setRefreshHeader(new ClassHeader_other(this));
        swipe_layout.setOnRefreshListener(this);
        swipe_layout.setOnLoadmoreListener(this);
        et_send.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() <= 0) {
                  isRePlyUSer=false;
                    CID=null;
                    et_send.setHint("");
                } else {

                }
            }
        });
    }

    private void initList() {
        Map<String, String> map = new HashMap<>();
        map.put("nid", newsid);
        map.put("type", type);
        map.put("Page", Page + "");
        map.put("PageSize", PageSize + "");
        map.put("siteid", InterfaceJsonfile.SITEID);
        if (spu.getUser() != null) {
            map.put("uid", spu.getUser().getUid());
        }
        map.put("deivce", DeviceUtils.getMyUUID(activity));
        LogUtils.e(newsid+"--"+type+"--"+Page+"--"+PageSize+"--"+DeviceUtils.getMyUUID(activity));
        Factory.provideHttpService().AllNewsComment(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<CommEntity, Boolean>() {
                    @Override
                    public Boolean call(CommEntity commEntity) {
                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<CommEntity>() {
                    @Override
                    public void call(CommEntity commEntity) {
                        disMissDialog();
                        if (mFlagRefresh) {
                            swipe_layout.finishRefresh();
                            swipe_layout.setLoadmoreFinished(true);//恢复上拉状态
                        }
                        LogUtils.e("code---" + commEntity.data);
                        if (commEntity.code.equals("200")) {

                            setListData(commEntity.data);

                            LogUtils.e("code" + list.size() + "");

                            adapter.notifyDataSetChanged();
                            ll_empty.setVisibility(View.GONE);
                        } else {
                            if (Page==1){
                                ll_empty.setVisibility(View.VISIBLE);
                            }else {
                                TUtils.toast(commEntity.msg);
                                ll_empty.setVisibility(View.GONE);
                            }


                        }
                    }
                });
    }

    public void setListData(List<CommBean> list) {
        if (mFlagRefresh) {
            adapter.setNewData(list);
            adapter.notifyDataSetChanged();
        } else {
            adapter.addData(list);
            adapter.notifyDataSetChanged();
            adapter.loadMoreComplete();
        }
        LogUtils.i("size-->" + adapter.getData().size());
        if (list.size() < PageSize) {
            //关闭刷新
            adapter.loadMoreEnd(true);
        }
    }

//    @Override
//    public void onLoadMoreRequested() {
//        Page++;
//        initList();
//        swipe_layout.setLoadmoreFinished(true);
//    }
    @OnClick(R.id.tv_send)
    public void Send(View view){
        switch (view.getId()){
            case R.id.tv_send:
                if (spu.getUser()==null){
                    PageCtrl.start2LoginActivity(activity);
                }else {
                    sendComment(et_send.getText().toString().trim(),CID);
                }
                break;
        }
    }


//    private void sendComment(String content, String cid) {
//
//        Map<String, String> map = new HashMap<>();
//        map.put("nid", nid);
//        map.put("uid", spu.getUser().getUid());
//        map.put("type", newstype);
//        map.put("title", nid);
//        map.put("content", content);
//        map.put("cid", cid);
//        map.put("json_url", "fsdfsdfsfs");//随便传一个
//        map.put("siteid", InterfaceJsonfile.SITEID);
//        Factory.provideHttpService()
//                .newsComment(ParamUtils.getRequestParam(map))
//                .onBackpressureBuffer()
//                .subscribeOn(Schedulers.io())
//                .filter(new Func1<ComResultEntity, Boolean>() {
//                    @Override
//                    public Boolean call(ComResultEntity entity) {
//                        LogUtils.i("200-->" + entity.code);
//                        if ("200".equals(entity.code)) {
//                            LogUtils.i("200-->成功");
//                            return true;
//                        }
//                        LogUtils.i("200失败");
//                        return false;
//                    }
//                })
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Action1<ComResultEntity>() {
//                    @Override
//                    public void call(ComResultEntity entity) {
//
//                        if ("200".equals(entity.code)) {
//                            TUtils.toast(entity.msg);
//                        } else {
//                            TUtils.toast(entity.msg);
//                        }
////                            setData();
//                    }
//                }, new Action1<Throwable>() {
//                    @Override
//                    public void call(Throwable throwable) {
//                        TUtils.toast("评论失败");
//
//                    }
//                });
//    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        activity.unregisterReceiver(getUserInfobr);
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        refreshlayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                Page = 1;
                mFlagRefresh = true;
                initList();
                swipe_layout.finishRefresh();
                swipe_layout.setLoadmoreFinished(false);
            }
        },2000);
    }
//    //发表评论接口
//    private void sendComment(String content, String cid) {
//        showDialog();
//        Map<String, String> map = new HashMap<>();
//        map.put("nid", ndb.getNid());
//        map.put("uid", spu.getUser().getUid());
//        map.put("type", "NEWS");
//        map.put("cid", cid);
//        map.put("content", content);
//        map.put("title", ndb.getTitle());
//        map.put("json_url", ndb.getNewsurl());//随便传一个
//        map.put("siteid", InterfaceJsonfile.SITEID);
//        Factory.provideHttpService()
//                .newsComment(ParamUtils.getRequestParam(map))
//                .onBackpressureBuffer()
//                .subscribeOn(Schedulers.io())
//                .filter(new Func1<ComResultEntity, Boolean>() {
//                    @Override
//                    public Boolean call(ComResultEntity entity) {
//                        LogUtils.i("200-->" + entity.code);
//                        if ("200".equals(entity.code)) {
//                            LogUtils.i("200-->成功");
//                            return true;
//                        }
//                        LogUtils.i("200失败");
//                        return false;
//                    }
//                })
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Action1<ComResultEntity>() {
//                    @Override
//                    public void call(ComResultEntity entity) {
//                        disMissDialog();
//                        if ("200".equals(entity.code)) {
//                            TUtils.toast("评论成功");
//                            et_send.setText("");
//                            ll_empty.setVisibility(View.GONE);
//                        } else {
//                            TUtils.toast(entity.msg);
//                        }
////                            setData();
//                    }
//                }, new Action1<Throwable>() {
//                    @Override
//                    public void call(Throwable throwable) {
//                        TUtils.toast("评论失败");
//                        disMissDialog();
//                    }
//                });
//    }

    //发表评论接口
    private void sendComment(String content, String cid) {
        showDialog();
        Map<String, String> map = new HashMap<>();
        map.put("nid", ndb.getNid());
        map.put("uid", spu.getUser().getUid());
        map.put("type", newstype);
        map.put("cid", cid);
        map.put("content", content);
        map.put("title", ndb.getTitle());
        map.put("json_url", ndb.getNewsurl());//随便传一个
        map.put("siteid", InterfaceJsonfile.SITEID);
        LogUtils.i("nid-->"+ndb.getNid());
        LogUtils.i("nid-->"+spu.getUser().getUid());
        LogUtils.i("nid-->"+newstype);
        LogUtils.i("nid-->"+cid);
        LogUtils.i("nid-->"+content);
        LogUtils.i("nid-->"+ndb.getTitle());
        LogUtils.i("nid-->"+ndb.getNewsurl());

        Factory.provideHttpService()
                .newsComment(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<ComResultEntity, Boolean>() {
                    @Override
                    public Boolean call(ComResultEntity entity) {
                        LogUtils.i("200-->" + entity.code);
                        if ("200".equals(entity.code)) {
                            LogUtils.i("200-->成功");
                            return true;
                        }
                        LogUtils.i("200失败");
                        return false;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<ComResultEntity>() {
                    @Override
                    public void call(ComResultEntity entity) {
                        disMissDialog();
                        if ("200".equals(entity.code)) {
                            TUtils.toast(entity.msg);
                            et_send.setText("");
                            ll_empty.setVisibility(View.GONE);
                        } else {
                            TUtils.toast(entity.msg);
                        }
//                            setData();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        TUtils.toast("评论失败");
                        disMissDialog();
                    }
                });
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        Page++;
        swipe_layout.finishLoadmore();
        initList();

        swipe_layout.setLoadmoreFinished(true);
    }


    public class GetUserInfo extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(SEND_MSG)) {

                CID=intent.getStringExtra("cid");
                USERNANME=intent.getStringExtra("username");

                et_send.setText("回复："+USERNANME);


            }else if (action.equals(PRASE)){
                f_position=intent.getIntExtra("f_position",0);
                position=intent.getIntExtra("position",0);
                String count=adapter.getItem(f_position).getChildren().get(position).getPraise();
                int cou=Integer.parseInt(count);
                adapter.getItem(f_position).getChildren().get(position).setPraise((cou+1)+"");
                adapter.getItem(f_position).setIspraise("1");
            }
        }
    }


}
